package com.animationsp.acs.action;

import org.apache.commons.codec.net.URLCodec;

import com.animationsp.acs.util.Constant;
import com.animationsp.acs.util.MyActionSupport;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.config.Config;
import com.qiniu.api.rs.GetPolicy;
import com.qiniu.api.rs.URLUtils;

public class DownloadAction extends MyActionSupport {
	// input
	private String key; //
	
	// output
	private String downloadUrl;
	
	@Override
	public String execute() throws Exception {
		System.out.println("Download key: "+key);
		key = new String(key.getBytes("iso8859-1"),"utf-8"); // tomcat默认编码是iso8859-1，所以收到的是该编码的参数，先转成utf-8的
		System.out.println("Download key: "+key);
		key = qiniuescape(key);
		System.out.println("Download key: "+key);
		URLCodec urlEncoder = new URLCodec("UTF-8");
		System.out.println("Download key encoded: "+urlEncoder.encode(key).replaceAll("\\+", "%20"));
		if(Constant.AUTHORITY.equals(Constant.PUBLIC)){
			downloadUrl = "http://"+Constant.BUCKET+".u.qiniudn.com/"+urlEncoder.encode(key).replaceAll("\\+", "%20"); // replaceAll("+", "%20"),encode之后空格会变成+号，七牛需要的是空格即%20
			// downloadUrl = Constant.BUCKET+".u.qiniudn.com/"+key;
		}else{
			Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
	        // String baseUrl = URLUtils.makeBaseUrl(Constant.BUCKET+".u.qiniudn.com", urlEncoder.encode(key));
	        String baseUrl = URLUtils.makeBaseUrl(Constant.BUCKET+".u.qiniudn.com", key);
	        GetPolicy getPolicy = new GetPolicy();
	        downloadUrl = getPolicy.makeRequest(baseUrl, mac);
	        System.out.println(downloadUrl);
		}	
        
		return SUCCESS;
	}
	
	/**
	 * 带有/ 或 @ 的特殊的key的转义
	 * 首字符为'/'转为"@/" ， "//"转为"/@/" ，"/@"转为"/@@"
	 * @param key
	 * @return
	 * @see http://kb.qiniu.com/52slk76w
	 */
	private String qiniuescape(String key){
		char[] chars = key.toCharArray();
		StringBuilder sb = new StringBuilder();
		boolean needescape = true;
		for(char c : chars){
			if(c == '/' && needescape){
				sb.append("@/");
			}else if(c == '@' && needescape){
				sb.append("@@");
			}else{
				sb.append(c);
			}
			needescape = (c == '/');
		}
		return sb.toString();
	}
	
	public static void main(String[] args) throws Exception {
        Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
        String baseUrl = URLUtils.makeBaseUrl("aspcs.u.qiniudn.com", "<key>");
        GetPolicy getPolicy = new GetPolicy();
        String downloadUrl = getPolicy.makeRequest(baseUrl, mac);
        System.out.println(downloadUrl);
    }


	public String getDownloadUrl() {
		return downloadUrl;
	}


	public void setDownloadUrl(String downloadUrl) {
		this.downloadUrl = downloadUrl;
	}


	public String getKey() {
		return key;
	}


	public void setKey(String key) {
		this.key = key;
	}
	
	
}
